<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/29.
 */

namespace App\Http\Controllers\Traits;

use App\Exceptions\CommonExceptionConstants;
use App\Exceptions\ServiceException;
use App\Utils\ResultsVo;

trait EditTrait
{
    public function edit($id): \Illuminate\Http\JsonResponse
    {
        $data = request()->all();
        if (method_exists($this, 'validated')) {
            $this->validated();
        }
        if (method_exists($this, 'beforeEdit')) {
            $data = $this->beforeEdit($data);
        }
        $model = modelBuild($this->getModel());
        $dao = $model->newQuery()->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::NO_FIND_DATA);
        }
        $dao->update($data);
        if (method_exists($this, 'afterEdit')) {
            $this->afterEdit($dao);
        }

        return ResultsVo::success();
    }
}
